﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using Infragistics.Win.UltraWinGrid;

namespace DMSClient.General
{
    public partial class User : Form
    {

        WSHttpBinding httpBinding = new WSHttpBinding();
        EndpointAddress address = new EndpointAddress(Properties.Settings.Default.Server);
        string pass = "";
        string idUser = "";
        DataSet ds;
        DataTable dt;
        bool creado = false;

        public User()
        {
            InitializeComponent();

            httpBinding.MaxReceivedMessageSize = 2147483647;
            httpBinding.MaxBufferPoolSize = 2147483647;
            httpBinding.CloseTimeout = TimeSpan.MaxValue;
            httpBinding.ReceiveTimeout = TimeSpan.MaxValue;
            httpBinding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            httpBinding.Security.Mode = SecurityMode.None;
        }

        private void User_Load(object sender, EventArgs e)
        {
            uceStatus.SelectedIndex = 0;
            uceRoles.ValueMember = "IdRole";
            uceRoles.DisplayMember = "dsName";
            DMSServices.DMSServicesClient cliente = new DMSServices.DMSServicesClient(httpBinding, address);
            string roles;
            try
            {
                cliente.Open();
                roles = cliente.getRols();
                cliente.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
            }
            if (roles == null)
            {
                throw new Exception(Properties.Settings.Default.DistributorsNullListErrorMsg);
            }
            DataTable dt = new DataTable("rolesDT");
            dt.Columns.Add("IdRole");
            dt.Columns.Add("cdRole");
            dt.Columns.Add("dsName");

            DataSet ds = new DataSet();
            ds.Tables.Add(dt);

            System.IO.StringReader xmlSR = new System.IO.StringReader(roles);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            uceRoles.DataSource = ds.Tables[0];
            uceRoles.SelectedIndex = 0;
            uceStatus.SelectedIndex = 0;
            xmlSR.Close();
        }

        private void ubSave_Click(object sender, EventArgs e)
        {
            int res = 0;
            bool encriptar = false;
            DMSServices.DMSServicesClient cliente = new DMSServices.DMSServicesClient(httpBinding, address);
            if (uteUsername.Text.Equals("")) {
                MessageBox.Show(this, "Username cannot be empty", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (utePass.Text.Equals("") && pass.Trim().Equals(""))
            {
                MessageBox.Show(this, "Password cannot be empty", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else if (!utePass.Text.Trim().Equals(""))
            {
                pass = utePass.Text;
                encriptar = true;
            }
            try
            {
                cliente.Open();
                res = cliente.setUser(idUser, uteUsername.Text, uteName.Text, pass, uteEmail.Text, uteSkype.Text, uteMSN.Text, utePhone.Text, utePhone2.Text, int.Parse(uceRoles.Value.ToString()), uceStatus.Value.ToString(), encriptar);
                cliente.Close();
            }
            catch (Exception ex) {
                
                if (idUser.Equals(""))
                {
                    MessageBox.Show(this, "Error trying to create user, can't acces to server. Check your network connection.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show(this, "Error trying to update user, can't acces to server. Check your network connection.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            
            if (res>0)
            {
                MessageBox.Show(this,"Operation Successful", this.Text, MessageBoxButtons.OK, MessageBoxIcon.None);
                if (!idUser.Equals("")) creado = true;
                validarUsuario();
            }
            else if (res == 0)
            {
                if (idUser.Equals(""))
                {
                    MessageBox.Show(this, "Error while creating user", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show(this, "Error while updating user", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            else {
                MessageBox.Show(this, "Server side error", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void uteUsername_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) {
                validarUsuario();
            }
        }

        private void uteUsername_Leave(object sender, EventArgs e)
        {
            validarUsuario();
        }

        private void limpiarForm() {
            uteName.Text = "";
            utePass.Text = "";
            utePhone.Text = "";
            utePhone2.Text = "";
            uteEmail.Text = "";
            uteMSN.Text = "";
            uteSkype.Text = "";
        }

        private void validarUsuario() {
            pass = "";
            idUser = "";
            limpiarForm();
            DMSServices.DMSServicesClient cliente = new DMSServices.DMSServicesClient(httpBinding, address);
            string user;
            try
            {
                cliente.Open();
                user = cliente.getUserbyUserName(uteUsername.Text);
                cliente.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, Properties.Settings.Default.ReportErrorMsg, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (user == null) {
                MessageBox.Show(this, Properties.Settings.Default.ReportNullErrorMsg, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            } 

            DataTable dt = new DataTable("userDT");
            dt.Columns.Add("IdUser");
            dt.Columns.Add("dsName");
            dt.Columns.Add("dsUserName");
            dt.Columns.Add("dsPassword");
            dt.Columns.Add("dsEmail");
            dt.Columns.Add("dsSkype");
            dt.Columns.Add("dsMSN");
            dt.Columns.Add("dsPhone1");
            dt.Columns.Add("dsPhone2");
            dt.Columns.Add("idRole");
            dt.Columns.Add("idStatus");
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            System.IO.StringReader xmlSR = new System.IO.StringReader(user);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();

            if (dt.Rows.Count > 0)
            {
                idUser = dt.Rows[0]["IdUser"].ToString();
                uteName.Text = dt.Rows[0]["dsName"].ToString();
                uteEmail.Text = dt.Rows[0]["dsEmail"].ToString();
                uteSkype.Text = dt.Rows[0]["dsSkype"].ToString();
                uteMSN.Text = dt.Rows[0]["dsMSN"].ToString();
                utePhone.Text = dt.Rows[0]["dsPhone1"].ToString();
                utePhone2.Text = dt.Rows[0]["dsPhone2"].ToString();
                uceRoles.Value = dt.Rows[0]["idRole"].ToString();
                uceStatus.Value = dt.Rows[0]["idStatus"].ToString();
                pass = dt.Rows[0]["dsPassword"].ToString();
            }
            else {
                idUser = "";
                uteName.Text = "";
                uteEmail.Text = "";
                uteSkype.Text = "";
                uteMSN.Text = "";
                utePhone.Text = "";
                utePhone2.Text = "";
                pass = "";
            }
        }

        private void ultraButton1_Click(object sender, EventArgs e)
        {
            if (ubUsers.Text.Equals("Show Users"))
            {
                this.Size = new System.Drawing.Size(665, 462);
                ugbUsers.Visible = true;
                ubUsers.Text = "Hide Users";
                this.MaximizeBox = true;
                this.FormBorderStyle = FormBorderStyle.Sizable;
                ubExport.Visible = true;
                if (ugUsers.Rows.Count <1 || creado)
                {
                    backgroundWorker1.RunWorkerAsync();
                    loader1.Visible = true;
                }
            }
            else {
                ubUsers.Text = "Show Users";
                ugbUsers.Visible = false;
                this.MaximizeBox = false;
                this.FormBorderStyle = FormBorderStyle.FixedDialog;
                this.WindowState = FormWindowState.Normal;
                this.Size = new System.Drawing.Size(480, 254);
                ubExport.Visible = false;
            }
            
        }

        private void ubExport_Click(object sender, EventArgs e)
        {
            if (ugUsers.Rows.Count < 1)
            {
                MessageBox.Show(this, "There is no data to export", "Users Report", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            System.Windows.Forms.SaveFileDialog dialogo = new System.Windows.Forms.SaveFileDialog();
            dialogo.DefaultExt = "xls";
            Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter Exporter = new Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter();
            if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Exporter.Export(ugUsers, dialogo.FileName);
                if (MessageBox.Show(this, "Do you want to open the file?", "Users Report", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(dialogo.FileName);
                }
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            DMSServices.DMSServicesClient cliente = new DMSServices.DMSServicesClient(httpBinding, address);
            BackgroundWorker worker = sender as BackgroundWorker;
            string listarUser;
            try
            {
                cliente.Open();
                listarUser = cliente.getUsers();
                cliente.Close();
                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.ReportErrorMsg, ex.InnerException);
            }
            if (listarUser == null) throw new Exception(Properties.Settings.Default.ReportNullErrorMsg);


            dt = new DataTable("usersDT");

            dt.Columns.Add("IdUser");
            dt.Columns.Add("Username");
            dt.Columns.Add("Name");
            dt.Columns.Add("Rol");
            dt.Columns.Add("e-mail");
            dt.Columns.Add("Skype");
            dt.Columns.Add("MSN");
            dt.Columns.Add("Phone1");
            dt.Columns.Add("Phone2");

            ds = new DataSet("usersDS");
            ds.Tables.Add(dt);

            System.IO.StringReader xmlSR = new System.IO.StringReader(listarUser);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            xmlSR.Close();
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                ugUsers.DataSource = dt;
                loader1.Visible = false;
            }
        }

        private void centrarLoader()
        {
            loader1.Left = (this.Width - loader1.Width) / 2;
            loader1.Top = ((this.Height - loader1.Height) / 2) - loader1.Height;
        }

        private void User_Resize(object sender, EventArgs e)
        {
            centrarLoader();
        }

        private void User_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (backgroundWorker1.IsBusy) backgroundWorker1.CancelAsync();
        }

        private void ugUsers_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            foreach (UltraGridColumn ugc in e.Layout.Bands[0].Columns)
            {
                ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
            }
        }

        private void ugUsers_DoubleClickRow(object sender, DoubleClickRowEventArgs e)
        {
            uteUsername.Text = ugUsers.ActiveRow.Cells["Username"].Value.ToString();
            validarUsuario();
        }

    }
}
